using System.Linq.Expressions;
using System.Reflection;

namespace Dapper.Bulk;

public class EntityMapping<T> where T : class
{
    public string TableName { get; set; } = typeof(T).Name.ToLower() + "s";
    public PropertyInfo? IdentityProperty { get; set; }
    public List<PropertyInfo> Properties { get; set; } = new();
    public BulkOptions BulkOptions { get; set; } = new();
    
    public EntityMapping()
    {
        // 默认获取所有公共属性，但排除复杂类型
        Properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .Where(p => p.CanRead && p.CanWrite && IsSimpleType(p.PropertyType))
            .ToList();
    }

    private static bool IsSimpleType(Type type)
    {
        return type.IsPrimitive ||
               type.IsEnum ||
               type == typeof(string) ||
               type == typeof(decimal) ||
               type == typeof(DateTime) ||
               type == typeof(DateTimeOffset) ||
               type == typeof(TimeSpan) ||
               type == typeof(Guid) ||
               Nullable.GetUnderlyingType(type) != null && IsSimpleType(Nullable.GetUnderlyingType(type)!);
    }

    public EntityMapping<T> Table(string tableName)
    {
        TableName = tableName;
        return this;
    }

    public EntityMapping<T> Identity<TProperty>(Expression<Func<T, TProperty>> expression)
    {
        if (expression.Body is MemberExpression memberExpression)
        {
            IdentityProperty = memberExpression.Member as PropertyInfo;
        }
        return this;
    }

    public EntityMapping<T> UseBulkOptions(Action<BulkOptions> configure)
    {
        configure(BulkOptions);
        return this;
    }
}